package test.swing;

import java.io.IOException;

/**
 * @Description TODO(这里用一句话描述这个类的作用)
 *
 * @author liuqinghua
 * @date 2023-8-30
 */

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import org.knowm.xchart.BitmapEncoder;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.XYChart;
import org.knowm.xchart.XYChartBuilder;
import org.knowm.xchart.XYSeries;
import org.knowm.xchart.BitmapEncoder.BitmapFormat;
import org.knowm.xchart.style.Styler.ChartTheme;
import org.knowm.xchart.style.markers.SeriesMarkers;

public class Example {

    public static void main(String[] args) throws IOException {

        // 创建Chart
        XYChart chart = new XYChartBuilder().width(800).height(600).theme(ChartTheme.Matlab).title("Matlab Theme")
                .xAxisTitle("X").yAxisTitle("Y").build();

        // 添加数据源
        chart.getStyler().setPlotGridLinesVisible(false);
        chart.getStyler().setXAxisTickMarkSpacingHint(100);

        // Series
        List<Integer> xData = new ArrayList<Integer>();
        for (int i = 0; i < 640; i++) {
            xData.add(i);
        }
        List<Double> y1Data = getYAxis(xData, 320, 160);
        List<Double> y2Data = getYAxis(xData, 320, 320);
        List<Double> y3Data = new ArrayList<Double>(xData.size());
        for (int i = 0; i < 640; i++) {
            y3Data.add(y1Data.get(i) - y2Data.get(i));
        }

        XYSeries series = chart.addSeries("Gaussian 1", xData, y1Data);
        series.setMarker(SeriesMarkers.NONE);
        series = chart.addSeries("Gaussian 2", xData, y2Data);
        series.setMarker(SeriesMarkers.NONE);
        series = chart.addSeries("Difference", xData, y3Data);
        series.setMarker(SeriesMarkers.NONE);

        BitmapEncoder.saveBitmap(chart, "d:/poi/aaa", BitmapFormat.PNG);
        String s = "data:image/png;base64,"
                + Base64.getEncoder().encodeToString(BitmapEncoder.getBitmapBytes(chart, BitmapFormat.PNG));
        System.out.println(s);
        // 进行展示
        new SwingWrapper<XYChart>(chart).displayChart();

    }

    private static List<Double> getYAxis(List<Integer> xData, double mean, double std) {

        List<Double> yData = new ArrayList<Double>(xData.size());

        for (int i = 0; i < xData.size(); i++) {
            yData.add((1 / (std * Math.sqrt(2 * Math.PI)))
                    * Math.exp(-(((xData.get(i) - mean) * (xData.get(i) - mean)) / ((2 * std * std)))));
        }
        return yData;
    }

}